/*
* Copyright (c) 2025 Huawei Device Co., Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including but not limited to the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to provide persons with access to the Software
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGE OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

import React, { useState, useEffect, useRef, ReactElement } from 'react';
import { BreakpointManager } from '@hadss/web_adaptive_layout_ui';
import { MultiGridRow, MultiGridCol } from '@hadss/web_adaptive_layout_react'; // React version of these components
import PlaylistHeader from './components/PlaylistHeader';
import PlaylistHeaderTable from './components/PlaylistHeaderTable';
import CurPlaySong from './components/CurPlaySong';
import { songs } from './model';
import './index.css';
import backIcon from '../../assets/playList/back.png';
import playIcon from '../../assets/playList/play_icon.png';
import showAllIcon from '../../assets/playList/show_all.png';
import acousticIcon from '../../assets/playList/acoustic.png';
import songItemIcon from '../../assets/playList/song_item_icon.png';
import {
  AvoidArea,
  AvoidAreaInfo,
  AvoidAreaType,
} from '../../common/windowCommon';

const SongTable = (): ReactElement => {
  const unsubscribe = useRef<(() => void) | null>(null);
  const breakpointManagerRef = useRef(new BreakpointManager());
  const breakpointManager = breakpointManagerRef.current;
  const isLargerPage = useRef(false);
  const distanceBorderLeft = useRef(16);
  const distanceBorderRight = useRef(16);
  const distanceTableTop = useRef(0);
  const songIconLeft = useRef(0);
  const [topAvoidArea, setTopAvoidArea] = useState(0);
  const [bottomAvoidArea, setBottomAvoidArea] = useState(0);
  // 列表滑动区域的高度
  const [tableListStyle, setTableListStyle] = useState({
    height: `calc(100vh - ${distanceTableTop.current}px)`,
  });

  useEffect(() => {
    const unsubscribe = breakpointManager.subscribeToBreakpoint(() => {
      isLargerPage.current = breakpointManager.useBreakpointValue({
        md: false,
        lg: true,
      });
      distanceBorderLeft.current = breakpointManager.useBreakpointValue({
        sm: 16,
        md: 24,
      });
      distanceBorderRight.current = breakpointManager.useBreakpointValue({
        sm: 16,
        md: 0,
      });
      distanceTableTop.current = breakpointManager.useBreakpointValue({
        md: 320,
        lg: 100,
      });
      songIconLeft.current = breakpointManager.useBreakpointValue({
        sm: 0,
        md: 24,
      });
    });
    setAvoidValue();
    window.addEventListener('avoidAreaChange', handleAvoidAreaChange);

    return (): void => {
      if (unsubscribe) {
        unsubscribe();
      }
      window.removeEventListener('avoidAreaChange', handleAvoidAreaChange);
    };
  }, []);

  // 屏幕大小改变的时候，列表滑动区域的高度也实时更新
  useEffect(() => {
    const handleResize = (): void => {
      setTableListStyle({
        height: `calc(100vh - ${distanceTableTop.current}px)`,
      });
    };
    handleResize();
    window.addEventListener('resize', handleResize);
    return (): void => window.removeEventListener('resize', handleResize);
  }, [distanceTableTop]);

  //  返回
  const goBack = (): void => {
    window.history.back();
  };

  const handleAvoidAreaChange = (event: any): void => {
    const data = event.detail as AvoidAreaInfo;
    const areaType = data.type;
    if (areaType === AvoidAreaType.TYPE_SYSTEM) {
      const topAvoidArea = (window as any).webClass?.pxToVp(
        data.area.topRect.height
      );
      setTopAvoidArea(topAvoidArea);
    }
    if (areaType === AvoidAreaType.TYPE_NAVIGATION_INDICATOR) {
      const bottomAvoidArea = (window as any).webClass?.pxToVp(
        data.area.bottomRect.height
      );
      setBottomAvoidArea(bottomAvoidArea);
    }
  };

  const setAvoidValue = (): void => {
    if ((window as any).webClass) {
      const webClass = (window as any).webClass;
      const topArea = webClass.getAvoidArea(
        AvoidAreaType.TYPE_SYSTEM
      ) as AvoidArea;
      const bottomArea = webClass.getAvoidArea(
        AvoidAreaType.TYPE_NAVIGATION_INDICATOR
      ) as AvoidArea;
      const topAvoidArea = webClass.pxToVp(topArea.topRect.height);
      const bottomAvoidArea = webClass.pxToVp(bottomArea.bottomRect.height);
      setTopAvoidArea(topAvoidArea);
      setBottomAvoidArea(bottomAvoidArea);
    }
  };
  return (
    <div className="playList-container">
      {isLargerPage.current && (
        <div
          className="go-back-out"
          onClick={goBack}
          style={{
            paddingTop: `${topAvoidArea ? topAvoidArea : 8}px`,
          }}
        >
          <img src={backIcon} className="go-back" alt="Go back" />
        </div>
      )}
      <div>
        <div className={isLargerPage.current ? 'containerOtherObj' : ''}>
          {!isLargerPage.current && (
            <PlaylistHeader
              songsLength={songs.length}
              topAvoidArea={topAvoidArea}
            />
          )}
          {isLargerPage.current && <PlaylistHeaderTable bottomAvoidArea={bottomAvoidArea}/>}
          <div className="listOut">
            {isLargerPage.current && (
              <div className="list-header">
                <img src={playIcon} className="list-header-image" alt="Play" />
                <span className="list-header-text">播放全部</span>
                <span className="list-header-text">{songs.length}</span>
                <div className="flex-style" />
                <img src={showAllIcon} className="open-icon" alt="Show all" />
              </div>
            )}
            <div className="table-list" style={tableListStyle}>
              <div
                style={{
                  marginLeft: `${distanceBorderLeft.current}px`,
                  marginRight: `${distanceBorderRight.current}px`,
                  width: 'auto',
                }}
              >
                <MultiGridRow
                  columns={{ xs: 12, sm: 12, md: 12, lg: 8, xl: 8 }}
                  gutter={{ x: { xs: 0, sm: 0, md: 24, lg: 24, xl: 24 } }}
                >
                  {songs.map((item, index) => (
                    <MultiGridCol
                      key={index}
                      className="song-item"
                      span={{ xs: 12, sm: 12, md: 6, lg: 4, xl: 4 }}
                    >
                      <div className="song-info">
                        <div className="song-title">{item.title}</div>
                        <div className="artist-container">
                          <img
                            src={acousticIcon}
                            className="acoustic"
                            alt="Acoustic"
                          />
                          <div className="song-artist">{item.artist}</div>
                        </div>
                      </div>
                      <div className="flex-style" />
                      <img
                        src={songItemIcon}
                        className="song-icon"
                        style={{ paddingRight: `${songIconLeft.current}px` }}
                        alt="Song options"
                      />
                    </MultiGridCol>
                  ))}
                  <MultiGridCol>
                    <div
                      style={{
                        height: bottomAvoidArea ? '120px' : '70px',
                      }}
                    ></div>
                  </MultiGridCol>
                </MultiGridRow>
              </div>
            </div>
          </div>
        </div>
      </div>
      <CurPlaySong song={songs[0]} bottomAvoidArea={bottomAvoidArea} />
    </div>
  );
};

export default SongTable;
